import { Button, DatePicker, Form, Input, InputNumber, message, Modal, Select } from 'antd';
import moment from 'moment';
import React, { PureComponent } from 'react';
import styles from '@/common/PateoTable/TableList.less';
import {merchantsType, transOption} from '@/utils/enums';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const merchantsOpt = transOption(merchantsType)

export default class MerchantEditModal extends PureComponent {
  state = {
    buttonLoading: false,
    form: React.createRef(),
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  setData = data => {
    const { form } = this.state;
    form.current &&
      form.current.setFieldsValue({
        ...data,
        type: String(data.type),
      });
  };

  ok = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { form } = this.state;
    form.current
      .validateFields()
      .then(values => {
        this.setLoading(true);
        let req = Object.assign({}, values);
        // 去除商户账号前后空格并重新设置到表单字段中
        req['merchantName'] = req['merchantName'].trim();
        req.startDate = moment(req.rangeDate[0]).format('YYYY-MM-DD');
        req.endDate = moment(req.rangeDate[1]).format('YYYY-MM-DD');
        delete req.rangeDate;
        dispatch({
          type: 'common/queryPost',
          payload: {
            url: '/mscreditbusiness/merchants/manage',
            ...req,
            type: req.type
          },
          callback: response => {
            this.setLoading(false);
            if (response.statusCode === '0') {
              message.success('新增成功');
              dispatch({
                type: 'common/pageablePost',
                payload: { url: '/mscreditbusiness/merchants/manage/list', delFlag: 0 },
              });
              this.close();
            } else {
              // message.error(response.statusMessage);
            }
          },
        });
      })
      .catch(err => {
      });
  };

  setLoading = flag => {
    this.setState({
      buttonLoading: flag,
    });
  };

  close = () => {
    const { closeModal } = this.props;
    const { form } = this.state;
    form.current.resetFields();
    this.setState({
      buttonLoading: false,
    });
    closeModal();
  };
  validateMerchantName = (rule, value, callback) => {
    const trimmedValue = (value ?? '').trim(); // 去除前后空格
    if (!trimmedValue) {
      callback('请填写商户账号');
    } else {
      // 继续其他校验逻辑，例如长度校验等
      // 如果通过校验，调用 callback() 不传递参数即可
      callback();
    }
  };
  renderSimpleForm() {
    const { modalVisible } = this.props;
    const { buttonLoading } = this.state;
    const footer = (
      <div>
        <Button onClick={this.close} size="small">
          取消
        </Button>
        <Button loading={buttonLoading} onClick={this.ok} size="small" type="primary">
          确定
        </Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <Modal
        footer={footer}
        title={'新增商户'}
        visible={modalVisible}
        onCancel={this.close}
        style={{ top: 50 }}
        width={600}
      >
        <Form ref={this.state.form} style={{ marginTop: 12 }} >
          <FormItem
            name="type"
            rules={[{ required: true, message: '请选择商户类型' }]}
            {...formItemLayout}
            label="商户类型"
          >
            <Select options={merchantsOpt} placeholder={"请选择商户类型"}/>
          </FormItem>
          <FormItem
            name="name"
            rules={[{ required: true, message: '请填写商户名称' }]}
            {...formItemLayout}
            label="商户名称"
          >
            <Input maxLength={30} placeholder="请填写商户名称" />
          </FormItem>
          <FormItem
            name={'merchantName'}
            rules={[
              { required: true, validator: this.validateMerchantName },
              { max: 64, message: '商户账号最长不能超过64个字符' },
            ]}
            {...formItemLayout}
            label="商户账号"
          >
            <Input maxLength={64} placeholder="请填写商户账号" />
          </FormItem>
          <FormItem
            name={'merchantPhone'}
            rules={[
              { required: true, message: '请填写商户负责人手机号' },
              {
                message: '请填写正确的手机号',
                whitespace: true,
                pattern: /^1[0-9][0-9]\d{8}$/,
              },
            ]}
            {...formItemLayout}
            label="商户负责人手机号"
          >
            <Input maxLength={11} placeholder="请填写商户负责人手机号" />
          </FormItem>
          <FormItem
            name={'merchantUserMail'}
            rules={[
              {
                required: true,
                message: '请填写正确的邮箱格式',
                pattern:
                  /^[A-Za-z\d]+([-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[-\.])+[A-Za-z\d]{2,4}(,[A-Za-z\d]+([-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[-\.])+[A-Za-z\d]{2,4})*$/,
              },
            ]}
            {...formItemLayout}
            label="商户邮箱"
          >
            <Input maxLength={64} placeholder="请填写商户邮箱" />
          </FormItem>
          <FormItem
            name={'rangeDate'}
            rules={[{ required: true, message: '请填写商户有效期' }]}
            {...formItemLayout}
            label="商户有效期"
          >
            <RangePicker
              placeholder={['合作开始日', '合作截止日']}
              format="YYYY-MM-DD"
              allowClear
              style={{ width: 'auto' }}
            />
          </FormItem>
          <FormItem name={'address'} {...formItemLayout} label="商户地址">
            <Input maxLength={50} placeholder="请填写商户地址" />
          </FormItem>
          <FormItem
            name={'servicePhone'}
            rules={[
              {
                // required: true,
                message: '请填写正确的电话号码',
                pattern: /^1[1|3-9][0-9]{9}$/,
              },
            ]}
            {...formItemLayout}
            label="商户客服电话"
          >
            <Input maxLength={11} placeholder="请填写商户客服电话" />
          </FormItem>

          <FormItem
            name={'adminMail'}
            rules={[
              {
                required: false,
                message: '请填写正确的邮箱格式',
                pattern:
                  /^[A-Za-z\d]+([-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[-\.])+[A-Za-z\d]{2,4}(,[A-Za-z\d]+([-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[-\.])+[A-Za-z\d]{2,4})*$/,
              },
            ]}
            {...formItemLayout}
            label="管理联系人邮箱"
          >
            <Input maxLength={64} placeholder="请填写管理联系人邮箱" />
          </FormItem>
          <FormItem name={'remarks'} {...formItemLayout} label="备注">
            <Input placeholder="请填写备注" />
          </FormItem>
        </Form>
      </Modal>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return <div className={styles.tableListForm}>{this.renderForm()}</div>;
  }
}
